package org.jeecg.modules.lidyhxx.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.apache.http.entity.ContentType;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.agCarGps.entity.AgCarGps;
import org.jeecg.modules.lidyhxx.entity.Lidyhxx;
import org.jeecg.modules.lidyhxx.service.ILidyhxxService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import sun.misc.BASE64Decoder;


/**
 * @Description: 理达用户信息
 * @Author: jeecg-boot
 * @Date: 2020-11-24
 * @Version: V1.0
 */
@Api(tags = "理达用户信息")
@RestController
@RequestMapping("/lidyhxx/lidyhxx")
@Slf4j
public class LidyhxxController extends JeecgController<Lidyhxx, ILidyhxxService> {
    @Autowired
    private ILidyhxxService lidyhxxService;

    @Autowired
    RestTemplate restTemplate;

    @Value("${lida.picUrl}")
    String picUrl ;
    @Value("${lida.renylbUrl}")
    String renylbUrl;
    @Value("${lida.bumUrl}")
    String bumUrl;
    @Value("${lida.userUrl}")
    String userUrl;


    @GetMapping(value = "/syncData")
    void lid() {

        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", "1");
         map.put("pageSize", "99999");
        //map.put("pageSize", "100");

        //用户信息
        //JSONObject jsonObject = restTemplate.postForObject("http://172.18.51.33:18081/sdata/rest/service/dataapi/rest/c85b624d-50bd-497e-9894-d1a861bdcf79", map, JSONObject.class);
        //xgw
        JSONObject jsonObject = restTemplate.postForObject(userUrl, map, JSONObject.class);
        System.out.println("$$$$$$$" + jsonObject + "\n");

        JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("result"));
        //	 System.out.println("jsonarray"+jsonArray);
        ArrayList<Lidyhxx> lidyhxx = new ArrayList<Lidyhxx>();
        for (int i = 0; i < jsonArray.size(); i++) {
            System.out.println(jsonArray.size());
            System.out.println(i);
            System.out.println();

            Lidyhxx lidyhxx1 = new Lidyhxx();
            if (jsonArray.getJSONObject(i).keySet().contains("MEMBER_CODE")) {
                lidyhxx1.setMemberCode(jsonArray.getJSONObject(i).getString("MEMBER_CODE"));
            }
            String s = null;
            //照片信息
            //  if (lidyhxx1.getMemberId() != null && !lidyhxx1.getMemberId().equals("")) {
            //xgw
            if (lidyhxx1.getMemberCode() != null && !lidyhxx1.getMemberCode().equals("")) {

                Map<String, Object> pic = new HashMap<>();
                //  map2.put("MEMBER_ID", lidyhxx1.getMemberId());
                //xgw
                pic.put("MEMBER_CODE", lidyhxx1.getMemberCode());

                // JSONObject jsonObject2 = restTemplate.postForObject("http://172.18.51.33:18081/sdata/rest/service/dataapi/rest/d7e4de6d-3774-480b-9d43-ceb6ab660e09", pic, JSONObject.class);
                //xgw

                JSONObject jsonObject2 = restTemplate.postForObject(picUrl, pic, JSONObject.class);

                JSONArray jsonArray2 = JSONArray.fromObject(jsonObject2.get("result"));

                if (!jsonArray2.isEmpty()) {
                    String photo = jsonArray2.getJSONObject(0).getString("PHOTO");

//						System.out.println("照片信息" + jsonArray2);
//						System.out.println("照片信息2" + s);

                    //  String fileName = lidyhxx1.getMemberId() + ".jpeg";
                    //xgw
                    String fileName = lidyhxx1.getMemberCode() + ".jpeg";
                 //  String path = System.getProperty("java.io.tmpdir");
                    String path ="D:/tmp" ;
                    File File = new File(path);
                    if (!File.exists()) {
                        File.mkdirs();
                    }


                   String tmpPath = path + File.separator + fileName;
                  //  String tmpPath = path +"/" + fileName;
                    if (photo != null) { // 图像数据不为空
                        //Base64字节码解码为文件
                        GenerateImage(photo, tmpPath);
                    }
                    //上传minio
                    s = upFile(tmpPath,fileName);
                    System.out.println("理达url" + s);

                    lidyhxx1.setTupdz(s);

//                    File file = new File(tmpPath);
//
//                    // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
//                    if (file.exists() && file.isFile()) {
//                        if (file.delete()) {
//                            System.out.println("删除文件" + fileName + "成功！");
//
//                        } else {
//                            System.out.println("删除文件" + fileName + "失败！");
//
//                        }
//                    } else {
//                        System.out.println("删除文件失败：" + fileName + "不存在！");
//
//                    }
                }

            }

            if (s != null) {
                System.out.println("~~~~~~~~~~~" + s);


                if (jsonArray.getJSONObject(i).keySet().contains("MEMBER_NAME")) {
                    lidyhxx1.setMemberName(jsonArray.getJSONObject(i).getString("MEMBER_NAME"));
                }

                if (jsonArray.getJSONObject(i).keySet().contains("RETIRED_TIME")) {
                    // lidyhxx1.setRetiredTime(jsonArray.getJSONObject(i).getString("RETIRED_TIME"));
                    lidyhxx1.setRetiredTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("RETIRED_TIME")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("IDESTATUS_NO")) {
                    lidyhxx1.setIdestatusNo(jsonArray.getJSONObject(i).getString("IDESTATUS_NO"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("ENLIST_DATE")) {
                    // lidyhxx1.setEnlistDate(jsonArray.getJSONObject(i).getString("ENLIST_DATE"));
                    lidyhxx1.setEnlistDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("ENLIST_DATE")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("SERIAL_NO")) {
                    lidyhxx1.setSerialNo(jsonArray.getJSONObject(i).getString("SERIAL_NO"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("DIPLOMA")) {
                    lidyhxx1.setDiploma(jsonArray.getJSONObject(i).getString("DIPLOMA"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("SEX")) {
                    lidyhxx1.setSex(jsonArray.getJSONObject(i).getString("SEX"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("DEPT_NO")) {
                    lidyhxx1.setDeptNo(jsonArray.getJSONObject(i).getString("DEPT_NO"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("WORK_DATE")) {
                    // lidyhxx1.setWorkDate(jsonArray.getJSONObject(i).getString("WORK_DATE"));
                    lidyhxx1.setWorkDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("WORK_DATE")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("DUTY_RATING")) {
                    lidyhxx1.setDutyRating(jsonArray.getJSONObject(i).getString("DUTY_RATING"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("NATION")) {
                    lidyhxx1.setNation(jsonArray.getJSONObject(i).getString("NATION"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("STATUS")) {
                    lidyhxx1.setStatus(jsonArray.getJSONObject(i).getString("STATUS"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("BIRTH")) {
                    //  lidyhxx1.setBirth(jsonArray.getJSONObject(i).getString("BIRTH"));
                    lidyhxx1.setBirth(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("BIRTH")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("VALIDITY")) {
                    // lidyhxx1.setValidity(jsonArray.getJSONObject(i).getString("VALIDITY"));
                    lidyhxx1.setValidity(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("VALIDITY")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("UP_DATE")) {
                    lidyhxx1.setUpDate(jsonArray.getJSONObject(i).getString("UP_DATE"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("DOMICILE")) {
                    lidyhxx1.setDomicile(jsonArray.getJSONObject(i).getString("DOMICILE"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("BANK_NUMBER")) {
                    lidyhxx1.setBankNumber(jsonArray.getJSONObject(i).getString("BANK_NUMBER"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("UPDATE_TIME")) {
                    // lidyhxx1.setUptime(jsonArray.getJSONObject(i).getString("UPDATE_TIME"));
                    lidyhxx1.setUptime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(jsonArray.getJSONObject(i).getString("UPDATE_TIME")))));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("RANK_LEVEL")) {
                    lidyhxx1.setRankLevel(jsonArray.getJSONObject(i).getString("RANK_LEVEL"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("IDENTITY_CARD")) {
                    lidyhxx1.setIdentityCard(jsonArray.getJSONObject(i).getString("IDENTITY_CARD"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("MEMBER_ID")) {
                    lidyhxx1.setMemberId(jsonArray.getJSONObject(i).getString("MEMBER_ID"));
                }
                if (jsonArray.getJSONObject(i).keySet().contains("ACCOUNT_NO")) {
                    lidyhxx1.setAccountNo(jsonArray.getJSONObject(i).getString("ACCOUNT_NO"));
                }


                //人员类别
                if (lidyhxx1.getIdestatusNo() != null && !lidyhxx1.getIdestatusNo().equals("")) {
                    Map<String, Object> reny = new HashMap<>();
                    reny.put("IDESTATUS_NO", lidyhxx1.getIdestatusNo());
                    // JSONObject jsonReny = restTemplate.postForObject("http://172.18.51.33:18081/sdata/rest/service/dataapi/rest/2cda02b6-8253-4ab6-839b-2190458f774c", reny, JSONObject.class);
                    //xgw
                    JSONObject jsonReny = restTemplate.postForObject(renylbUrl, reny, JSONObject.class);

                    JSONArray jsonArrayReny = JSONArray.fromObject(jsonReny.get("result"));
                    String renylb = jsonArrayReny.getJSONObject(0).getString("IDE_DESCRIPTION");

                    lidyhxx1.setIdestatusNo(renylb);

                }
                //部门
                if (lidyhxx1.getDeptNo() != null && !lidyhxx1.getDeptNo().equals("")) {
                    Map<String, Object> bum = new HashMap<>();
                    bum.put("DEPT_NO", lidyhxx1.getDeptNo());
                    // JSONObject jsonBum = restTemplate.postForObject("http://172.18.51.33:18081/sdata/rest/service/dataapi/rest/720d36fe-65db-4f01-acfd-ab8949a8ad0b", bum, JSONObject.class);
                    //xgw
                    JSONObject jsonBum = restTemplate.postForObject(bumUrl, bum, JSONObject.class);

                    JSONArray jsonArrayBum = JSONArray.fromObject(jsonBum.get("result"));
                    String bumen = jsonArrayBum.getJSONObject(0).getString("DEPT_DESCRIPTION");
                    lidyhxx1.setDeptNo(bumen);
                }

                Lidyhxx lidyhxx2 = lidyhxxService.getOne(new QueryWrapper<Lidyhxx>().eq("identity_card", lidyhxx1.getIdentityCard()));
                if (lidyhxx2 != null) {
                    lidyhxxService.updateById(lidyhxx1);
                } else {
                    lidyhxxService.save(lidyhxx1);
                }

            }
        }

    }

    private void GenerateImage(String photo, String tmpPath) {// 对字节数组字符串进行Base64解码并生成图片

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码

            byte[] bytes = decoder.decodeBuffer(photo);
//            for (int i = 0; i < bytes.length; ++i) {
//                if (bytes[i] < 0) {// 调整异常数据
//                    bytes[i] += 256;
//                }
//            }
            // 生成jpeg图片


            FileOutputStream out = new FileOutputStream(tmpPath);
            out.write(bytes);
            out.flush();
            out.close();

        } catch (Exception e) {

        }

    }

    @RequestMapping(value = "up")
    public String upFile(String path,String fileName) {

        String filepath = path;//D盘下的file文件夹的目录
        File file = new File(filepath);//File类型可以是文件也可以是文件夹
        String url = null;
            try {
                url= MinioUtil.upload(new FileInputStream(new File(filepath)), fileName);
                System.out.println("我的*************************"+url+"\n");
            } catch (Exception e) {
                System.out.println(e.getMessage());

            }

       // }
        return url;
    }


    /**
     * 分页列表查询
     *
     * @param lidyhxx
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "理达用户信息-分页列表查询")
    @ApiOperation(value = "理达用户信息-分页列表查询", notes = "理达用户信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(Lidyhxx lidyhxx,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<Lidyhxx> queryWrapper = QueryGenerator.initQueryWrapper(lidyhxx, req.getParameterMap());
        Page<Lidyhxx> page = new Page<Lidyhxx>(pageNo, pageSize);
        IPage<Lidyhxx> pageList = lidyhxxService.page(page, queryWrapper);

        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param lidyhxx
     * @return
     */
    @AutoLog(value = "理达用户信息-添加")
    @ApiOperation(value = "理达用户信息-添加", notes = "理达用户信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Lidyhxx lidyhxx) {
        lidyhxxService.save(lidyhxx);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param lidyhxx
     * @return
     */
    @AutoLog(value = "理达用户信息-编辑")
    @ApiOperation(value = "理达用户信息-编辑", notes = "理达用户信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Lidyhxx lidyhxx) {
        lidyhxxService.updateById(lidyhxx);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "理达用户信息-通过id删除")
    @ApiOperation(value = "理达用户信息-通过id删除", notes = "理达用户信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        lidyhxxService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "理达用户信息-批量删除")
    @ApiOperation(value = "理达用户信息-批量删除", notes = "理达用户信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.lidyhxxService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "理达用户信息-通过id查询")
    @ApiOperation(value = "理达用户信息-通过id查询", notes = "理达用户信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Lidyhxx lidyhxx = lidyhxxService.getById(id);
        if (lidyhxx == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(lidyhxx);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lidyhxx
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Lidyhxx lidyhxx) {
        return super.exportXls(request, lidyhxx, Lidyhxx.class, "理达用户信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Lidyhxx.class);
    }

}
